import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-26
 * Time: 16:37
 */
//客户端
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    /**
     * 构造函数
     * @param serverIp 服务器的IP地址,也就是请求的目的ip
     * @param serverPort 服务器的端口号，请求的目的端口
     * @throws SocketException 创建Socket对象时可能会抛出此异常
     */
    //请求的源ip就是客户端的本机ip，请求的源端口就是系统随机分配的空闲端口
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //创建Socket对象,不指定端口，让系统自动分配一个空闲端口
        socket = new DatagramSocket();
    }
    //启动客户端
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        /*
        1.从控制台读取要发送的请求数据
        2.将请求数据封装成DatagramPacket对象，然后发送
        3.读取服务器的响应
        4.将响应数据显示在控制台上
         */
        while (true){
            System.out.print("-> ");//提示用户输入
            //1.从控制台读取要发送的请求数据
            if(!scanner.hasNext()){ //是否有下一个输入
                break;
            }
            String request = scanner.next();
            //2.将请求数据封装成DatagramPacket对象，然后发送
            //InetAddress.getByName(serverIp)是通过serverIp字符串（如"127.0.0.1"或"localhost"）解析得到目标服务器的IP地址对象
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //3.读取服务器的响应
            //创建一个DatagramPacket对象，用于接收服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.将响应数据显示在控制台上
            //将响应字节数组转化为字符串
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println("收到响应：" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
